#include "binary_cross_entropy_grad_custom_tiling.h"
#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue


class KernelBinaryCrossEntropyGrad{
public:
    __aicore__ inline KernelBinaryCrossEntropyGrad() {}
    __aicore__ inline void Init(GM_ADDR logits, GM_ADDR labels, GM_ADDR grad, GM_ADDR weight, GM_ADDR outgrad, BinaryCrossEntropyGradCustomTilingData tiling)
    {   
        
        if (tiling.isEvenCore)
        {
            this->blockLength = tiling.blockLength;
            this->blockLengthPlusIdx = tiling.blockLength * AscendC::GetBlockIdx();
            this->tileNum = tiling.tileNum;
            this->tileLength = tiling.tileLength / BUFFER_NUM;
            this->lastTileLength = tiling.lastTileLength;    
        }
        else
        {
            if (AscendC::GetBlockIdx() < tiling.formerNum)
            {
                this->blockLength = tiling.formerLength;
                this->blockLengthPlusIdx = tiling.formerLength * AscendC::GetBlockIdx();
                this->tileNum = tiling.formerTileNum;
                this->tileLength = tiling.formerTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.formerLastTileLength;
            }
            else
            {
                this->blockLength = tiling.tailLength;
                this->blockLengthPlusIdx = tiling.formerLength * tiling.formerNum +tiling.tailLength * (AscendC::GetBlockIdx() - tiling.formerNum);
                this->tileNum = tiling.tailTileNum;
                this->tileLength = tiling.tailTileLength / BUFFER_NUM;
                this->lastTileLength = tiling.tailLastTileLength;
            }
        }
        logitsGm.SetGlobalBuffer((__gm__ float *)logits + this->blockLengthPlusIdx, this->blockLength);
        labelsGm.SetGlobalBuffer((__gm__ float *)labels + this->blockLengthPlusIdx, this->blockLength);
        gradGm.SetGlobalBuffer((__gm__ float *)grad + this->blockLengthPlusIdx, this->blockLength);
        weightGm.SetGlobalBuffer((__gm__ float *)weight + this->blockLengthPlusIdx, this->blockLength);
        outgradGm.SetGlobalBuffer((__gm__ float *)outgrad + this->blockLengthPlusIdx, this->blockLength);
        pipe.InitBuffer(inQueueLogits, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(inQueueLabels, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(inQueueGrad, BUFFER_NUM, this->tileLength * sizeof(float));
        pipe.InitBuffer(inQueueWeight, BUFFER_NUM, this->tileLength * sizeof(float));   
        pipe.InitBuffer(outQueueOutGrad, BUFFER_NUM, this->tileLength * sizeof(float));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            CopyIn(i);
            Compute(i);
            CopyOut(i);
        }
    }

private:
    
    __aicore__ inline void CopyIn(int32_t progress)
    {
        AscendC::LocalTensor<float> logitsLocal = inQueueLogits.AllocTensor<float>();
        AscendC::LocalTensor<float> labelsLocal = inQueueLabels.AllocTensor<float>();
        AscendC::LocalTensor<float> gradLocal = inQueueGrad.AllocTensor<float>();
        AscendC::LocalTensor<float> weightLocal = inQueueWeight.AllocTensor<float>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(logitsLocal, logitsGm[(progress - 2) * this->tileLength + this->lastTileLength], this->tileLength);
            AscendC::DataCopy(labelsLocal, labelsGm[(progress - 2) * this->tileLength + this->lastTileLength], this->tileLength);
            AscendC::DataCopy(gradLocal, gradGm[(progress - 2) * this->tileLength + this->lastTileLength], this->tileLength);
            AscendC::DataCopy(weightLocal, weightGm[(progress - 2) * this->tileLength + this->lastTileLength], this->tileLength);
        }
        else
        {
            AscendC::DataCopy(logitsLocal, logitsGm[progress * this->tileLength], this->tileLength);
            AscendC::DataCopy(labelsLocal, labelsGm[progress * this->tileLength], this->tileLength);
            AscendC::DataCopy(gradLocal, gradGm[progress * this->tileLength], this->tileLength);
            AscendC::DataCopy(weightLocal, weightGm[progress * this->tileLength], this->tileLength);
        }
        inQueueLogits.EnQue(logitsLocal);
        inQueueLabels.EnQue(labelsLocal);
        inQueueGrad.EnQue(gradLocal);
        inQueueWeight.EnQue(weightLocal);
    }
    
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<float> logitsLocal = inQueueLogits.DeQue<float>();
        AscendC::LocalTensor<float> labelsLocal = inQueueLabels.DeQue<float>();
        AscendC::LocalTensor<float> gradLocal = inQueueGrad.DeQue<float>();
        AscendC::LocalTensor<float> weightLocal = inQueueWeight.DeQue<float>();
        AscendC::LocalTensor<float> outgradLocal = outQueueOutGrad.AllocTensor<float>();
            
        AscendC::Sub(logitsLocal, logitsLocal, labelsLocal, this->tileLength);
        AscendC::Mul(logitsLocal, logitsLocal, gradLocal, this->tileLength);
        AscendC::Mul(outgradLocal, logitsLocal, weightLocal, this->tileLength);

        outQueueOutGrad.EnQue<float>(outgradLocal);
        inQueueLogits.FreeTensor(logitsLocal);
        inQueueLabels.FreeTensor(labelsLocal);
        inQueueGrad.FreeTensor(gradLocal);
        inQueueWeight.FreeTensor(weightLocal);
    }

    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<float> outgradLocal = outQueueOutGrad.DeQue<float>();
        if ((progress == (this->tileNum * BUFFER_NUM - 2)) || (progress == (this->tileNum * BUFFER_NUM - 1)))
        {
            AscendC::DataCopy(outgradGm[(progress - 2) * this->tileLength + this->lastTileLength], outgradLocal, this->tileLength);
        }
        else
        {
            AscendC::DataCopy(outgradGm[progress * this->tileLength], outgradLocal, this->tileLength);
        }
        outQueueOutGrad.FreeTensor(outgradLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueLogits;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueLabels;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueGrad;
    AscendC::TQue<AscendC::TPosition::VECIN, BUFFER_NUM> inQueueWeight;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueOutGrad;

    AscendC::GlobalTensor<float> logitsGm;
    AscendC::GlobalTensor<float> labelsGm;
    AscendC::GlobalTensor<float> gradGm;
    AscendC::GlobalTensor<float> weightGm;
    AscendC::GlobalTensor<float> outgradGm;

    uint32_t blockLength;
    uint32_t blockLengthPlusIdx;
    uint32_t tileNum;
    uint32_t tileLength;
    uint32_t lastTileLength;
};


extern "C" __global__ __aicore__ void binary_cross_entropy_grad_custom(GM_ADDR logits, GM_ADDR labels, GM_ADDR grad, GM_ADDR weight, GM_ADDR outgrad, BinaryCrossEntropyGradCustomTilingData tiling)
{
        KernelBinaryCrossEntropyGrad op;
        op.Init(logits, labels, grad, weight, outgrad, tiling);
        op.Process();
}
